#!/bin/bash

# 进入临时安装目录
cd "/tmp/services-manager-install"
# 显示当前目录
echo "当前目录：$(pwd)"

# 检查是否以root权限运行
if [ "$EUID" -ne 0 ]; then 
    echo "请使用root权限运行此脚本"
    exit 1
fi

# 检查系统是否使用systemd
if ! command -v systemctl >/dev/null 2>&1; then
    echo "此系统不支持systemd，无法安装服务"
    exit 1
fi

# 设置变量
NAME="ima"
CAPTION="IMA"
SERVICE_NAME="youdu-plugin-$NAME"
DESC="YouDu $CAPTION Service"
INSTALL_DIR="/opt/youdu_plugin/$NAME"
EXEC_NAME="start.exe"
USER="youdu_plugin"
GROUP="youdu_plugin"

# 检查是否已经存在该服务，如果存在就先停止服务，并卸载服务再开始安装过程
if systemctl is-active --quiet "$SERVICE_NAME"; then
    echo "服务 $SERVICE_NAME 已经在运行，正在停止服务..."
    systemctl stop "$SERVICE_NAME"
fi
# if systemctl is-enabled --quiet "$SERVICE_NAME"; then
#     echo "服务 $SERVICE_NAME 已经启用，正在卸载服务..."
#     systemctl disable "$SERVICE_NAME"
#     rm -f "/etc/systemd/system/$SERVICE_NAME.service"
# fi
# if [ -d "$INSTALL_DIR" ]; then
#     echo "安装目录 $INSTALL_DIR 已经存在，正在卸载..."
#     rm -rf "$INSTALL_DIR"
# fi


# # 创建用户和组
# if ! getent group "$GROUP" >/dev/null; then
#     groupadd "$GROUP"
# fi
# if ! getent passwd "$USER" >/dev/null; then
#     useradd -r -g "$GROUP" -d "$INSTALL_DIR" "$USER"
# fi

# # 创建安装目录
# mkdir -p "$INSTALL_DIR"
# # mkdir -p "$INSTALL_DIR/logs"

echo "正在复制文件..."
# 复制可执行文件
cp -r "." "$INSTALL_DIR/"
chmod +x "$INSTALL_DIR/$EXEC_NAME"

# # 设置目录权限
# chown -R "$USER:$GROUP" "$INSTALL_DIR"

# # 创建systemd服务文件
# cat > "/etc/systemd/system/$SERVICE_NAME.service" << EOF
# [Unit]
# Description=$DESC
# After=network.target

# [Service]
# Type=simple
# User=$USER
# Group=$GROUP
# WorkingDirectory=$INSTALL_DIR
# ExecStart=$INSTALL_DIR/$EXEC_NAME
# Restart=always
# RestartSec=10

# [Install]
# WantedBy=multi-user.target
# EOF

# # 重新加载systemd配置
# systemctl daemon-reload

# 启用并启动服务
# systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# 检查服务状态
echo "正在检查服务状态..."
systemctl status "$SERVICE_NAME"

echo "更新完成！"
echo "可以使用以下命令管理服务："
echo "启动服务：systemctl start $SERVICE_NAME"
echo "停止服务：systemctl stop $SERVICE_NAME"
echo "重启服务：systemctl restart $SERVICE_NAME"
echo "查看状态：systemctl status $SERVICE_NAME"
echo "查看日志：journalctl -u $SERVICE_NAME"
echo "卸载服务：systemctl disable $SERVICE_NAME && rm -f /etc/systemd/system/$SERVICE_NAME.service"
echo "卸载目录：rm -rf $INSTALL_DIR"
echo "卸载用户：userdel -r $USER"
echo "卸载组：groupdel $GROUP"